package com.kzj.xfxh.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;


import com.kzj.common.exception.XfxhApiException;
import com.kzj.common.re.Result;
import com.kzj.xfxh.entity.JsonParse;
import com.kzj.xfxh.entity.RoleContent;
import com.kzj.xfxh.entity.Text;
import com.kzj.xfxh.properties.XfxhProperties;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;

@Slf4j

public class XfxhApiPlusBySocket extends WebSocketListener {
    private  List<RoleContent> historyList; // 对话历史存储集合
    private static final Gson gson = new Gson();
    private static final String USER_PREFIX="user:";
    private static final String ASSISTANT_PREFIX="assistant:";
    private static final String UID_PREFIX="uid:";
    private boolean answerCompleteFlag=false;

    public XfxhProperties xfxhProperties;

    public  String question;
    public  String answer; // 大模型的答案汇总
    public  String user;
    public Consumer<Result> callbackFunction;
    public XfxhApiPlusBySocket(XfxhProperties xfxhProperties, String id, String question, List<RoleContent> historyList, Consumer<Result> callbackFunction)
    {
        this.xfxhProperties=xfxhProperties;
        this.user=id;
        this.question=question;
        this.historyList=historyList;
        this.callbackFunction=callbackFunction;
    }

    class MyThread extends Thread {
        private WebSocket webSocket;

        public MyThread(WebSocket webSocket) {
            this.webSocket = webSocket;
        }
        public void run() {
            log.info("讯飞星火api 调用");
            try {
                JSONObject requestJson=new JSONObject();
                JSONObject header=new JSONObject();  // header参数
                header.put("app_id",xfxhProperties.getAppId());
                header.put("uid",UID_PREFIX+user);
                JSONObject parameter=new JSONObject(); // parameter参数
                JSONObject chat=new JSONObject();
                chat.put("domain",xfxhProperties.getDomain());
                chat.put("temperature",xfxhProperties.getTemperature());
                chat.put("max_tokens",xfxhProperties.getMaxTokens());
                parameter.put("chat",chat);

                JSONObject payload=new JSONObject(); // payload参数
                JSONObject message=new JSONObject();
                JSONArray text=new JSONArray();
                // 历史问题获取
                if(historyList.size()>0){
                    for(RoleContent tempRoleContent:historyList){
//                        if(tempRoleContent.role.equals(USER_PREFIX+user)||tempRoleContent.role.equals(ASSISTANT_PREFIX+user))
                            text.add(JSON.toJSON(tempRoleContent));
                    }
                }
                // 最新问题
                RoleContent roleContent=new RoleContent();
                roleContent.role="user";
                roleContent.content=question;
                text.add(JSON.toJSON(roleContent));
                historyList.add(roleContent);
                message.put("text",text);
                payload.put("message",message);
                requestJson.put("header",header);
                requestJson.put("parameter",parameter);
                requestJson.put("payload",payload);
                log.info(requestJson.toString()); // 可以打印看每次的传参明细
                webSocket.send(requestJson.toString());
                // 等待服务端返回完毕后关闭
                while (true) {
                    Thread.sleep(50);
                    if (answerCompleteFlag) {
                        break;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            }
    }
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        MyThread myThread = new MyThread(webSocket);
        myThread.start();
    }
    public void webSocketClose(WebSocket webSocket)
    {
        webSocket.close(1000, "");
    }
    @Override
    public void onMessage(WebSocket webSocket, String text) {
        System.out.println(text);
        Result result=new Result();
        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
        Integer code=myJsonParse.header.code;
        Integer status=myJsonParse.header.status;
        String content="";
        if (code != 0) {
            log.error("发生错误，错误码为：" + code);
            log.error("本次请求的sid为：" + myJsonParse.header.sid);
            webSocketClose(webSocket);
        }

        List<Text> textList = myJsonParse.payload.choices.text;
        for (Text temp : textList) {
            content+=temp.content;
            answer=answer+temp.content;
        }

        if(code!=0)
        {
            result.setCode(0);
            result.setMsg("发生错误，错误码为：" + code+";本次请求的sid为：" + myJsonParse.header.sid);
        }
        else{
            result.setCode(status==2?2:1);
        }
        result.setData(content);
        callbackFunction.accept(result);
        if (status == 2) {
            log.info("回答结束\n**********************************************************************************************");
            if(canAddHistory()){
                RoleContent roleContent=new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(answer);
                historyList.add(roleContent);
            }else{
                historyList.remove(0);
                RoleContent roleContent=new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(answer);
                historyList.add(roleContent);
            }
            answerCompleteFlag=true;
            webSocketClose(webSocket);
        }

    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        try {
            if (null != response) {
                int code = response.code();
                log.error("onFailure code:" + code);
                log.error("onFailure body:" + response.body().string());
                if (101 != code) {
                    log.error("connection failed");
                    throw new XfxhApiException("connection failed");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private    boolean canAddHistory(){  // 由于历史记录最大上线1.2W左右，需要判断是能能加入历史
        int history_length=0;
        for(RoleContent temp:historyList){
            history_length=history_length+temp.content.length();
        }
        if(history_length>12000){
            historyList.remove(0);
            historyList.remove(1);
            historyList.remove(2);
            historyList.remove(3);
            historyList.remove(4);
            return false;
        }else{
            return true;
        }
    }

}